package RpcClient.impl;

import Decoder.CommonDecoder;
import Encoder.CommonEncoder;
import RpcClient.RpcClient;
import Serializer.impl.JsonSerializer;
import entity.RpcRequest;
import entity.RpcResponse;
import handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;

public class RpcClientNetty implements RpcClient {
    private static final Bootstrap bootstrap;
    //静态代码块 配置好 Netty 客户端
    static{
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new CommonDecoder())
                                .addLast(new CommonEncoder(new JsonSerializer()))
                                .addLast(new NettyClientHandler());
                    }
                });
    }

    @Override
    public Object sendRequest(RpcRequest rpcRequest, String host, int port) {
        try{
            //连接服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
            Channel channel = future.channel();

            if(channel != null){
                System.out.println("client 连接服务器成功");
                channel.writeAndFlush(rpcRequest).addListener(future1 -> {
                    if (future1.isSuccess()){
                        System.out.println("客户端发送消息成功");
                    }else{
                        System.out.println("客户端发送消息失败");
                    }
                });

                channel.closeFuture().sync();

                AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse");
                RpcResponse rpcResponse = channel.attr(key).get();

                return rpcResponse;
            }

        } catch (InterruptedException e) {
            System.out.println("发送消息时产生错误！");
            e.printStackTrace();
        }
        return null;
    }
}
